package com.simga.library.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
import java.util.*

/***
 *
 */
abstract class BindRecycAdapter<T : ViewDataBinding, M> : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    val mData = ArrayList<M>(1)
    protected var mView: RecyclerView? = null
    protected lateinit var mContext: Context
    protected var listener: ((binding: T, item: M, position: Int) -> Unit)? = null
    protected open fun normalViewId(): Int = 0

    override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        mContext = viewGroup.context
        return BaseViewHolder(viewGroup, normalViewId())
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val baseHolder = holder as BindRecycAdapter<*, *>.BaseViewHolder
        if (position < mData.size) {
            onBindViewHolder(baseHolder.binding as T, mData[position], holder, position)
            if (listener != null)
                baseHolder.itemView.setOnClickListener {
                    listener!!.invoke(baseHolder.binding, mData[baseHolder.layoutPosition], baseHolder.layoutPosition)
                }
        }
    }

    abstract fun onBindViewHolder(mBinding: T, itemData: M, holder: RecyclerView.ViewHolder, position: Int)

    override fun getItemCount(): Int {
        return mData.size
    }

    fun addData(data: List<M>, position: Int) {
        mData.addAll(data)
        notifyItemInserted(position)
    }
    fun addData(position: Int, vararg data: M) {
        mData.addAll(position, data.toList())
        notifyItemInserted(position)
    }
    fun setNewData(data: List<M>) {
        mData.clear()
        mData.addAll(data)
        notifyDataSetChanged()
    }
    fun addData(data: List<M>) {
        addData(data, mData.size)
    }
    fun addData(vararg data: M) {
        addData(mData.size, *data)
    }
    fun remove(t: M) {
        val indexOf = mData.indexOf(t)
        if (indexOf != -1)
            removeAt(indexOf)
    }

    fun removeAt(position: Int) {
        if (position < mData.size)
            mData.removeAt(position)
        notifyItemRemoved(position)
        notifyItemRangeChanged(position, mData.size - position)
    }

    fun setOnItemClickListener(listener: ((binding: T, item: M, position: Int) -> Unit)) {
        this.listener = listener
    }

    /**
     * adapter中的ViewHolder类，主要作用为构建item与其binding对象
     */
    inner class BaseViewHolder(viewGroup: ViewGroup, layoutId: Int) :
            RecyclerView.ViewHolder(DataBindingUtil.inflate<ViewDataBinding>(LayoutInflater.from(
                    viewGroup.context), layoutId, viewGroup, false).root) {
        val binding: T = DataBindingUtil.getBinding(this.itemView)!!
    }
}
